package com.hub.nio.socket.nio;


import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * @ author 令狐冲
 * @ date & time 2025/2/5 10:27
 */
public class FileZeroCopy {

    public static void main(String[] args) {
        try (RandomAccessFile sourceFile = new RandomAccessFile("source.txt", "r"); RandomAccessFile targetFile = new RandomAccessFile("target.txt", "rw")) {
            FileChannel sourceChannel = sourceFile.getChannel();
            FileChannel targetChannel = targetFile.getChannel();

            long transferredToBytes = sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
            System.out.println("文件传输成功，传输了 " + transferredToBytes + " 字节数据。");

            // 使用transferFrom()方法将数据从目标文件传输回源文件
            // 从目标文件的位置0开始，传输全部文件内容回源文件
            long transferredFromBytes = targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            System.out.println("数据回传成功，传输了 " + transferredFromBytes + " 字节数据。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
